﻿/*编译器VIsual Studio 2017*/

#include<stdio.h>
#include<stdlib.h>
typedef struct item {
	int a;
}Item;
typedef struct node {
	Item item;
	struct node * next;
}Node;
typedef Node * List;
void Initializelist(List * plist);//初始化链表
void AddNode(List * plist, Item item);//向链表末尾添加节点
void FindNode(const List * plist, Item item);//找到添加的节点，并插入
void Traverse(const List * plist, void(*pfun)(Item item));//遍历整个链表并执行pfun指向的函数
void EmptyTheList(List * plist);//释放内存
void PrintItem(Item item);
Node * make(Item item);
int main() {
	puts("1.向链表加入10个奇数。2.向链表加入偶数。3.打印链表。4.退出程序。");
	int n;
	List plist;
	scanf("%d", &n);
	while (n!='q')
	{
		if (n == 1)//初始化链表并向里放入20个奇数
		{
			Initializelist(&plist);
			for (size_t i = 1; i < 20; i = i + 2){
				Item temp;
				temp.a = i;
				AddNode(&plist, temp);
			}
			printf("//向链表添加奇数成功\n");
		}
		else if (n == 2)
		{
			printf("输入插入的数据(0-20间的偶数): ");
			int num;
			scanf("%d", &num);
			while (num%2!=0)
			{
				printf("输入插入的数据(0-20间的偶数): ");
				scanf("%d", &num);
			}
			Item temp2;
			temp2.a = num;
			FindNode(&plist, temp2);
			printf("//向链表插入偶数成功\n");
		}
		else if (n == 3)
		{
			printf("链表数据如下：\n");
			Traverse(&plist, PrintItem);
			puts(" ");
		}
		else if (n == 4)
		{
			printf("bye~\n");
			break;
		}
		fflush(stdin);
		scanf("%d", &n);
	}
	EmptyTheList(&plist);
	system("pause");
	return 0;
}

void Initializelist(List * plist)
{
	*plist = NULL;
}
void AddNode(List * plist, Item item) {
	Node * pnew = make(item);

	Node * temp = *plist;
	if (temp == NULL)
	{
		*plist = pnew;
	}
	else
	{
		while (temp->next != NULL &&temp->next != NULL)
			temp = temp->next;
		temp->next = pnew;
	}
}
void FindNode(const List * plist, Item item)
{
	if (plist == NULL)
		printf("QAQ");
	Node * temp = *plist;
	Node * pnew = make(item);
	while (temp->next != NULL && (*temp->next).item.a < item.a)
		temp = temp->next;
	pnew->next = temp->next;
	temp->next = pnew;
}
void Traverse(const List * plist, void(*pfun)(Item item)) {
	Node * temp = *plist;
	while (temp!=NULL)
	{
		(*pfun)(temp->item);
		temp = temp->next;
	}
}
void EmptyTheList(List * plist) {
	Node* pfree;
	while (*plist != NULL) {
		pfree = (*plist)->next;
		free(*plist);
		(*plist) = pfree;
	}
}
void PrintItem(Item item)
{
	printf("%d ", item.a);
}
Node * make(Item item) {
	Node* pnew = (Node*)malloc(sizeof(Node));
	pnew->item = item;
	pnew->next = NULL;
	return pnew;
}